// 自行车产品服务 - 三数据库协同工作
import BikeProduct from '../models/BikeProduct.js';
import BikeCommunity from '../models/BikeCommunity.js';
import { setCache, getCache, delCache, CACHE_PREFIX } from '../../config/multi-database.js';

class BikeProductService {
  // 获取产品详情（三数据库协同）
  static async getProductDetail(productId, userId = null) {
    try {
      // 1. 检查缓存
      const cacheKey = `${CACHE_PREFIX.PRODUCT}detail:${productId}`;
      const cached = await getCache(cacheKey);
      if (cached) {
        console.log('✅ 从缓存获取产品详情');
        return cached;
      }
      
      // 2. 从PostgreSQL获取产品基本信息
      const product = await BikeProduct.findById(productId, false);
      if (!product) {
        throw new Error('产品不存在');
      }
      
      // 3. 并行获取其他数据
      const [ratingStats, reviews, communityPosts] = await Promise.all([
        // 从MongoDB获取评分统计
        this.getProductRatingStats(productId),
        // 获取最新评价
        BikeCommunity.getProductReviews(productId, 1, 5),
        // 获取相关社区讨论
        this.getRelatedCommunityPosts(productId)
      ]);
      
      // 4. 记录用户行为（如果用户已登录）
      if (userId) {
        BikeCommunity.logUserBehavior({
          user_id: userId,
          action_type: 'view_product',
          target_id: productId,
          target_type: 'product',
          metadata: { category: product.category_name }
        }).catch(console.error);
      }
      
      // 5. 组装完整产品数据
      const productDetail = {
        ...product,
        rating_stats: ratingStats,
        recent_reviews: reviews.reviews,
        related_posts: communityPosts,
        specifications: typeof product.specifications === 'string' 
          ? JSON.parse(product.specifications) 
          : product.specifications
      };
      
      // 6. 缓存完整数据（30分钟）
      await setCache(cacheKey, productDetail, 1800);
      
      return productDetail;
      
    } catch (error) {
      console.error('获取产品详情失败:', error);
      throw error;
    }
  }
  
  // 获取产品评分统计
  static async getProductRatingStats(productId) {
    try {
      // 检查缓存
      const cacheKey = `${CACHE_PREFIX.PRODUCT}rating:${productId}`;
      const cached = await getCache(cacheKey);
      if (cached) {
        return cached;
      }
      
      // 从MongoDB获取
      const ratingStats = await BikeCommunity.updateProductRating(productId);
      
      if (ratingStats) {
        await setCache(cacheKey, ratingStats, 3600);
      }
      
      return ratingStats || {
        average_rating: 0,
        total_reviews: 0,
        rating_distribution: { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 }
      };
      
    } catch (error) {
      console.error('获取产品评分统计失败:', error);
      return {
        average_rating: 0,
        total_reviews: 0,
        rating_distribution: { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 }
      };
    }
  }
  
  // 获取相关社区帖子
  static async getRelatedCommunityPosts(productId, limit = 3) {
    try {
      const cacheKey = `${CACHE_PREFIX.PRODUCT}posts:${productId}`;
      const cached = await getCache(cacheKey);
      if (cached) {
        return cached;
      }
      
      // 这里可以扩展为根据产品标签搜索相关帖子
      const posts = await BikeCommunity.getCommunityPosts({
        tags: ['bike', 'cycling', 'product']
      }, 1, limit);
      
      await setCache(cacheKey, posts.posts, 3600);
      
      return posts.posts;
      
    } catch (error) {
      console.error('获取相关社区帖子失败:', error);
      return [];
    }
  }
  
  // 搜索产品（智能搜索）
  static async searchProducts(searchParams, userId = null) {
    try {
      const { keyword, filters, page, limit } = searchParams;
      
      // 1. 记录搜索行为
      if (userId && keyword) {
        BikeCommunity.logUserBehavior({
          user_id: userId,
          action_type: 'search',
          target_type: 'product',
          metadata: { keyword, filters }
        }).catch(console.error);
      }
      
      // 2. 执行搜索
      const searchResult = await BikeProduct.search(filters, page, limit);
      
      // 3. 并行获取每个产品的评分信息
      const productsWithRatings = await Promise.all(
        searchResult.products.map(async (product) => {
          const ratingStats = await this.getProductRatingStats(product.id);
          return {
            ...product,
            average_rating: ratingStats.average_rating,
            total_reviews: ratingStats.total_reviews
          };
        })
      );
      
      return {
        ...searchResult,
        products: productsWithRatings
      };
      
    } catch (error) {
      console.error('搜索产品失败:', error);
      throw error;
    }
  }
  
  // 创建采购订单（事务处理）
  static async createPurchaseOrder(orderData) {
    const { postgresPool } = await import('../config/multi-database.js');
    const client = await postgresPool.connect();
    
    try {
      await client.query('BEGIN');
      
      // 1. 检查库存
      for (const item of orderData.items) {
        const product = await BikeProduct.findById(item.product_id, false);
        if (!product || product.stock_quantity < item.quantity) {
          throw new Error(`产品 ${product?.name} 库存不足`);
        }
      }
      
      // 2. 创建订单
      const orderQuery = `
        INSERT INTO purchase_orders (
          wholesaler_id, total_amount, status, 
          shipping_address, payment_method, notes
        ) VALUES ($1, $2, $3, $4, $5, $6)
        RETURNING *
      `;
      
      const orderResult = await client.query(orderQuery, [
        orderData.wholesaler_id,
        orderData.total_amount,
        'pending',
        orderData.shipping_address,
        orderData.payment_method,
        orderData.notes
      ]);
      
      const order = orderResult.rows[0];
      
      // 3. 创建订单项
      for (const item of orderData.items) {
        const itemQuery = `
          INSERT INTO order_items (
            order_id, product_id, quantity, unit_price, total_price
          ) VALUES ($1, $2, $3, $4, $5)
        `;
        
        await client.query(itemQuery, [
          order.id,
          item.product_id,
          item.quantity,
          item.unit_price,
          item.quantity * item.unit_price
        ]);
        
        // 4. 更新库存
        await BikeProduct.updateStock(item.product_id, -item.quantity);
      }
      
      await client.query('COMMIT');
      
      // 5. 记录订单创建行为
      BikeCommunity.logUserBehavior({
        user_id: orderData.wholesaler_id,
        action_type: 'create_order',
        target_id: order.id,
        target_type: 'order',
        metadata: { 
          total_amount: orderData.total_amount,
          item_count: orderData.items.length 
        }
      }).catch(console.error);
      
      // 6. 清理相关缓存
      await delCache(`${CACHE_PREFIX.ORDER}user:${orderData.wholesaler_id}`);
      
      return order;
      
    } catch (error) {
      await client.query('ROLLBACK');
      console.error('创建采购订单失败:', error);
      throw error;
    } finally {
      client.release();
    }
  }
  
  // 获取热门产品推荐
  static async getProductRecommendations(userId = null, limit = 10) {
    try {
      const cacheKey = `${CACHE_PREFIX.PRODUCT}recommendations:${userId || 'anonymous'}`;
      const cached = await getCache(cacheKey);
      if (cached) {
        return cached;
      }
      
      let recommendations;
      
      if (userId) {
        // 个性化推荐：基于用户行为
        recommendations = await this.getPersonalizedRecommendations(userId, limit);
      } else {
        // 通用推荐：热门产品
        recommendations = await BikeProduct.getHotProducts(limit);
      }
      
      // 添加评分信息
      const recommendationsWithRatings = await Promise.all(
        recommendations.map(async (product) => {
          const ratingStats = await this.getProductRatingStats(product.id);
          return {
            ...product,
            average_rating: ratingStats.average_rating,
            total_reviews: ratingStats.total_reviews
          };
        })
      );
      
      // 缓存推荐结果（1小时）
      await setCache(cacheKey, recommendationsWithRatings, 3600);
      
      return recommendationsWithRatings;
      
    } catch (error) {
      console.error('获取产品推荐失败:', error);
      // 降级方案：返回热门产品
      return await BikeProduct.getHotProducts(limit);
    }
  }
  
  // 个性化推荐（基于用户行为）
  static async getPersonalizedRecommendations(userId, limit) {
    try {
      // 1. 获取用户行为分析
      const behaviorAnalysis = await BikeCommunity.getUserBehaviorAnalysis(userId, 30);
      
      // 2. 基于行为模式生成推荐（简化版）
      // 这里可以实现更复杂的推荐算法
      
      // 临时返回热门产品
      return await BikeProduct.getHotProducts(limit);
      
    } catch (error) {
      console.error('个性化推荐失败:', error);
      return await BikeProduct.getHotProducts(limit);
    }
  }
  
  // 获取业务统计
  static async getBusinessStats(period = '30d') {
    try {
      const cacheKey = `${CACHE_PREFIX.STATS}business:${period}`;
      const cached = await getCache(cacheKey);
      if (cached) {
        return cached;
      }
      
      const { postgresPool, redisClient } = await import('../config/multi-database.js');
      
      // 并行获取各类统计
      const [salesStats, userStats, productStats, realtimeStats] = await Promise.all([
        this.getSalesStats(period),
        this.getUserStats(period),
        this.getProductStats(),
        this.getRealtimeStats()
      ]);
      
      const businessStats = {
        sales: salesStats,
        users: userStats,
        products: productStats,
        realtime: realtimeStats,
        period,
        generated_at: new Date().toISOString()
      };
      
      // 缓存业务统计（15分钟）
      await setCache(cacheKey, businessStats, 900);
      
      return businessStats;
      
    } catch (error) {
      console.error('获取业务统计失败:', error);
      throw error;
    }
  }
  
  // 获取销售统计
  static async getSalesStats(period) {
    // 实现销售统计逻辑
    return {
      total_orders: 0,
      total_revenue: 0,
      average_order_value: 0
    };
  }
  
  // 获取用户统计
  static async getUserStats(period) {
    // 实现用户统计逻辑
    return {
      total_users: 0,
      active_users: 0,
      new_users: 0
    };
  }
  
  // 获取产品统计
  static async getProductStats() {
    // 实现产品统计逻辑
    return {
      total_products: 0,
      active_products: 0,
      out_of_stock: 0
    };
  }
  
  // 获取实时统计
  static async getRealtimeStats() {
    const { redisClient } = await import('../config/multi-database.js');
    
    const today = new Date().toISOString().split('T')[0];
    
    const [dailyVisits, onlineUsers] = await Promise.all([
      redisClient.hGet('stats:daily_visits', today),
      redisClient.keys('user:online:*')
    ]);
    
    return {
      daily_visits: parseInt(dailyVisits) || 0,
      online_users: onlineUsers ? onlineUsers.length : 0
    };
  }
}

export default BikeProductService;